package com.gta.edu.sdk.config;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.gta.edu.sdk.util.StringUtil;


public class GsonUtilDateTypeAdapter extends TypeAdapter<Date>{
	private SimpleDateFormat sdf = null;
	private String pattern = "yyyy-MM-dd HH:mm:ss";
	
	public GsonUtilDateTypeAdapter(String pattern) {
		super();
		this.pattern = pattern;
		sdf = new SimpleDateFormat(this.pattern);
	}
	
	public GsonUtilDateTypeAdapter() {
		super();
		sdf = new SimpleDateFormat(this.pattern);
	}
	
	@Override
	public void write(JsonWriter out, Date value) throws IOException {
		out.value(sdf.format(value));
	}

	@Override
	public Date read(JsonReader in) throws IOException {
		if (in.peek() == null) {  
			return null;  
		}  
		String str = in. nextString();  
		try {
			if (!StringUtil.isNullOrEmpty(str)) {
				return sdf.parse(str);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}
